package com.css.zfzx.sjcj.config.filter;

import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author dc
 * @date 2020-05-22
 * @since 1.0.0
 */
@Slf4j
public class AppFilter implements Filter {
    private static List<Pattern> patterns = new ArrayList();
    FilterConfig filterConfig = null;

    @Override
    public void init(FilterConfig filterConfig) {

        this.filterConfig = filterConfig;
        String ignoreUrl = filterConfig.getInitParameter("ignoreUrl");
        log.debug("忽略路径为,ignoreUrl={}", ignoreUrl);
        if (!PlatformObjectUtils.isEmpty(ignoreUrl)) {
            String[] ignoreUrlArray = ignoreUrl.split(",");
            String[] array = ignoreUrlArray;
            int ignoreUrlArrayLength = ignoreUrlArray.length;
            for(int i = 0; i < ignoreUrlArrayLength; ++i) {
                String ignore = array[i];
                Pattern pattern = Pattern.compile(ignore);
                patterns.add(pattern);
            }
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI().substring(request.getContextPath().length());
        log.debug("请求url={}", url);
        if(this.isIgnore(url)){
            log.debug("忽略路径,url={}", url);
            chain.doFilter(request, response);
        }else {
            String charset = filterConfig.getInitParameter("charset");
            if (PlatformObjectUtils.isEmpty(charset)) {
                charset = PlatformConstants.DEFAULT_CHARSET;
            }
            request.setCharacterEncoding(charset);
            response.setCharacterEncoding(charset);

            HttpSession session = request.getSession();
            String userId = (String) session.getAttribute(PlatformConstants.CUR_USER_ID_IN_SESSION);
            if (PlatformObjectUtils.isEmpty(userId)) {
                // userId不存在
                session.invalidate();
                log.debug("用户未登录,请求为ajax请求");
                response.getWriter().write("{\"code\":\"417\"}");
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }
    private boolean isIgnore(String url) {
        Iterator list = patterns.iterator();

        Matcher matcher;
        do {
            if (!list.hasNext()) {
                return false;
            }

            Pattern pattern = (Pattern)list.next();
            matcher = pattern.matcher(url);
        } while(!matcher.matches());

        return true;
    }
}
